# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(optparse)
library(stringr)
library(magrittr)
library(tidyverse)
library(tools)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))

configData

isInter <- configGet(configData, "isInter") %>%
  as.logical()

diffMetabolites <- configGet(configData, "diffFiles") %>%
  str_split(":") %>%
  unlist() %>%
  map(function(fileName) {
    newFileName <- fileName %>%
      str_split("/") %>%
      unlist() %>%
      tail(., 2) %>%
      str_c(collapse = "_") %>%
      str_replace(., ".csv$", ".txt")
    data <- read_tsv(str_c(newFileName))
    data$Metabolite
  })

metaboliteNames <- if (isInter) {
  diffMetabolites %>%
    Reduce(intersect, .)
}else {
  diffMetabolites %>%
    Reduce(union, .)
}

data <- read_tsv(opt$i) %>%
  filter(Metabolite %in% metaboliteNames)

write_csv(data, "Markers_Table.csv")

metaboliteNames

options(digits = 3)





















